import { useSyncExternalStore } from "react";

/**
 * 
 * @param key 存储到localStorage 的key
 * @param defaultValue 默认值
 */


// callback() 的核心作用就是通知 React "外部存储的数据变了，请立即更新组件"

export const useStorage = (key:any, defaultValue?:any) => { 
    const subscribe = (cb: () => void) =>{
        window.addEventListener('storage', (e)=>{
            console.log("触发了", e)
            cb();
        });
        return () => window.removeEventListener('storage', cb);
    }

     // 从localStorage中获取数据 如果读不到返回默认值
    const getSnapshot = () => {
        const value = localStorage.getItem(key)
        return (value ? JSON.parse(value) : null) || defaultValue
    }

    // 修改数据
    const setStorage = (value: any) => {
        localStorage.setItem(key, JSON.stringify(value))
        window.dispatchEvent(new Event('storage')) // 手动触发storage事件
    }

    // 返回数据
    const res = useSyncExternalStore(subscribe, getSnapshot)

    return [res, setStorage]
};